import cv2
import numpy as np
from PIL import ImageGrab

temp_list = [cv2.resize(cv2.imread(f'Template/{idx}.jpg', 0), (20, 20)) for idx in range(1, 10)]


def capture_screen(leftup,rightdown):
    # 获取全屏截图
    screenshot = ImageGrab.grab()

    # 设置要选取的区域（左上角为(x1, y1)，右下角为(x2, y2)）
    x1, y1 = leftup
    x2, y2 =rightdown
    region_of_interest = screenshot.crop((x1, y1, x2, y2))

    # 保存选取的区域到文件
    region_of_interest.save("new.jpeg")

def contours_filter(contours):
    """
    将cv2.findContours的结果筛选:
        - 首先保留长款比在0.8~1.2的contours
        - 然后保留面积大于所有contours面积均值的80%
    :param contours: cv2.findContours的结果
    :return:
    """
    # x, y, w, h = cv2.boundingRect(contour)
    contours = [contour for contour in contours if
                0.8 < (cv2.boundingRect(contour))[2] / (cv2.boundingRect(contour))[3] < 1.2]

    areas = [cv2.contourArea(contour) for contour in contours]
    areas_mean = sum(areas) / areas.__len__()
    filted_contours = [contour for contour in contours if cv2.contourArea(contour) >= areas_mean * 0.8]  # 按面积筛选

    return filted_contours


def match_temp(digital_img, threshold_value=200):
    """
    模板来源是特定分辨率下，扣除数字框二值化（200阈值）缩放为20*20，不同分别率下的数字图片可能有差异，和模板图片不一定耦合
    可以写一个函数，写入数字图片到本地，手动筛选重命名
    :param digital_img: RGB格式的数字图片
    :return:
    """
    # 对图像进行二值化
    _, binary_image = cv2.threshold(cv2.cvtColor(digital_img, cv2.COLOR_BGRA2GRAY), threshold_value, 255,
                                    cv2.THRESH_BINARY)
    binary_image = cv2.resize(binary_image, (20, 20))

    temp_match_res = [cv2.matchTemplate(binary_image, temp, cv2.TM_CCOEFF_NORMED) for temp in temp_list]
    match_rel_value = [cv2.minMaxLoc(res)[1] for res in temp_match_res]
    return match_rel_value.index(max(match_rel_value)) + 1


def find_best_selection(matrix):
    """
    在数字矩阵中寻找本次和为10的最多格子数方案
    :param matrix: 10*16格式的矩阵
    :return:
    """
    rows, cols = matrix.shape
    max_score = 0
    best_selection = None
    pos=[]

    for r in range(rows):
        for c in range(cols):
            for i in range(r, rows):
                for j in range(c, cols):
                    selected = matrix[r:i + 1, c:j + 1]
                    selected_sum = np.sum(selected)
                    selected_size = selected.size

                    if selected_sum == 10 and selected_size > max_score:
                        pos=[r,c,i,j]
                        max_score = selected_size
                        best_selection = selected

    return max_score, best_selection,pos


def show_contours(image, contours):
    draw_image = cv2.drawContours(np.zeros_like(image), contours, -1, (255, 255, 255), thickness=cv2.FILLED)
    cv2.imshow('draw_image', draw_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


def show_img(image):
    cv2.imshow('image', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
